using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TradeFlow.Server.Dto;
using TradeFlow.Server.Models;
using SqlSugar;
using TradeFlow.Server.Language;

namespace TradeFlow.Server.Service
{
    /// <summary>
    /// 对账单表体服务类
    /// </summary>
    public class JxAccountListService : IApplicationService
    {
        private readonly SugarRepository<JxAccountList> _repository;
        private readonly SugarRepository<JxAccountHead> _headRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="headRepository"></param>
        /// <param name="localizer"></param>
        public JxAccountListService(SugarRepository<JxAccountList> repository, SugarRepository<JxAccountHead> headRepository )
        {
            _repository = repository;
            _headRepository = headRepository;
        }

        /// <summary>
        /// 查询对账单表体分页列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<RestfulResult<object>> GetPagesAsync(JxAccountListPageParam param)
        {
            try
            {
                var query = _repository.AsQueryable();
                
                // 根据参数进行条件筛选
                if (!string.IsNullOrEmpty(param.HeadId))
                {
                    query = query.Where(x => x.HeadId == param.HeadId);
                }
                if (!string.IsNullOrEmpty(param.BillId))
                {
                    query = query.Where(x => x.BillId == param.BillId);
                }

                // 执行分页查询
                var result = await query.OrderBy(x => x.Id).ToPageListAsync(param.CurrentPage, param.PageSize);
                
                return new RestfulResult<object>()
                {
                    Data = result,
                    Code = 0,
                    Message = "查询成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "查询失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 获取所有对账单表体列表
        /// </summary>
        /// <returns></returns>
        public async Task<RestfulResult<object>> GetListAsync()
        {
            try
            {
                var list = await _repository.AsQueryable().ToListAsync();
                return new RestfulResult<object>()
                {
                    Data = list,
                    Code = 0,
                    Message = "查询成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "查询失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 根据表头ID获取表体列表
        /// </summary>
        /// <param name="headId"></param>
        /// <returns></returns>
        public async Task<RestfulResult<object>> GetByHeadIdAsync(long headId)
        {
            try
            {
                var list = await _repository.AsQueryable().Where(x => x.HeadId == headId.ToString()).ToListAsync();
                return new RestfulResult<object>()
                {
                    Data = list,
                    Code = 0,
                    Message = "查询成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "查询失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 增加对账单表体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> AddAsync(JxAccountList entity)
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrEmpty(entity.HeadId))
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "表头ID必填"
                    };
                }
                if (string.IsNullOrEmpty(entity.BillId))
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "单据ID必填"
                    };
                }

                // 检查表头是否存在且状态允许修改
                var headEntity = await _headRepository.AsQueryable().Where(x => x.Id == Convert.ToInt64(entity.HeadId)).FirstAsync();
                if (headEntity == null)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "账单不存在"
                    };
                }
                if (headEntity.Status != "暂存")
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "对账已确认，无法编辑"
                    };
                }

                // 检查单据是否已在其他对账单中
                var exists = await _repository.AsQueryable().Where(x => x.BillId == entity.BillId && x.HeadId != entity.HeadId).AnyAsync();
                if (exists)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "单据已在其他对账单中"
                    };
                }

                // 保存表体数据
                await _repository.InsertAsync(entity);

                // 更新表头总金额
                await UpdateHeadTotalAmount(Convert.ToInt64(entity.HeadId));

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "添加成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "添加失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 批量增加对账单表体
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> BatchAddAsync(List<JxAccountList> entities)
        {
            try
            {
                if (entities == null || entities.Count == 0)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "数据为空"
                    };
                }

                // 获取所有表头ID
                var headIds = entities.Select(x => x.HeadId).Distinct().ToList();
                if (headIds.Count > 1)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "批量添加必须使用相同表头"
                    };
                }

                string headId = headIds[0];

                // 检查表头是否存在且状态允许修改
                var headEntity = await _headRepository.AsQueryable().Where(x => x.Id == Convert.ToInt64(headId)).FirstAsync();
                if (headEntity == null)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "对账单表头不存在"
                    };
                }
                if (headEntity.Status != "暂存")
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "对账已确认，无法编辑"
                    };
                }

                // 获取所有要添加的单据ID
                var billIds = entities.Select(x => x.BillId).ToList();
                
                // 检查这些单据是否已在其他对账单中
                var exists = await _repository.AsQueryable().Where(x => billIds.Contains(x.BillId) && x.HeadId != headId).AnyAsync();
                if (exists)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "部分单据已在其他对账单中"
                    };
                }

                // 处理每个明细
                foreach (var entity in entities)
                {
                    // 验证必填字段
                    // 仅验证必填字段
                    if (string.IsNullOrEmpty(entity.HeadId))
                    {
                        return new RestfulResult<object>()
                        {
                            Code = 0,
                            Message = "表头ID必填"
                        };
                    }
                    if (string.IsNullOrEmpty(entity.BillId))
                    {
                        return new RestfulResult<object>()
                        {
                            Code = 0,
                            Message = "单据ID必填"
                        };
                    }
                }

                // 保存表体数据
                await _repository.InsertRangeAsync(entities);

                // 更新表头总金额
                await UpdateHeadTotalAmount(Convert.ToInt64(headId));

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "添加成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "添加失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 更新对账单表体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> UpdateAsync(JxAccountList entity)
        {
            try
            {
                // 检查是否存在
                var oldEntity = await _repository.AsQueryable().Where(x => x.Id == entity.Id).FirstAsync();
                if (oldEntity == null)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "数据不存在"
                    };
                }

                // 检查表头是否允许修改
                var headEntity = await _headRepository.AsQueryable().Where(x => x.Id == Convert.ToInt64(oldEntity.HeadId)).FirstAsync();
                if (headEntity == null)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "对账单表头不存在"
                    };
                }
                if (headEntity.Status != "暂存")
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "对账已确认，无法编辑"
                    };
                }

                // 验证必填字段
                // 验证必填字段
                if (string.IsNullOrEmpty(entity.HeadId))
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "表头ID必填"
                    };
                }
                if (string.IsNullOrEmpty(entity.BillId))
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "单据ID必填"
                    };
                }

                // 保持HeadId、BillId不变
                entity.HeadId = oldEntity.HeadId;
                entity.BillId = oldEntity.BillId;

                // 更新数据
                await _repository.UpdateAsync(entity);

                // 更新表头总金额
                await UpdateHeadTotalAmount(Convert.ToInt64(oldEntity.HeadId));

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "更新成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "更新失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 删除对账单表体
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> DeleteAsync(List<long> ids)
        {
            try
            {
                // 获取要删除的记录
                var entities = await _repository.AsQueryable().Where(x => ids.Contains(x.Id)).ToListAsync();
                if (entities.Count == 0)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "数据不存在"
                    };
                }

                // 获取所有表头ID
                var headIds = entities.Select(x => x.HeadId).Distinct().ToList();
                
                // 先检查表头状态，再执行删除

                foreach (var headId in headIds)
                {
                    // 检查表头是否允许修改
                    var headEntity = await _headRepository.AsQueryable().Where(x => x.Id == Convert.ToInt64(headId)).FirstAsync();
                    if (headEntity != null && headEntity.Status != "暂存")
                    {
                        return new RestfulResult<object>()
                        {
                            Code = 0,
                            Message = "对账已确认，无法编辑"
                        };
                    }
                }

                // 删除数据 - 直接传入List<long>，不进行转换
                await _repository.DeleteAsync(x => ids.Contains(x.Id));

                // 更新所有相关表头的总金额
                foreach (var headId in headIds)
                {
                    await UpdateHeadTotalAmount(Convert.ToInt64(headId));
                }

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "删除成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "删除失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 更新表头总金额
        /// </summary>
        /// <param name="headId"></param>
        private async Task UpdateHeadTotalAmount(long headId)
        {
            // 计算总金额
            // 由于JxAccountList没有TotalAmount字段，这里简单设置为0
            decimal totalAmount = 0;
            
            // 更新表头
            await _headRepository.AsUpdateable().SetColumns(x => new JxAccountHead { TotalAmount = totalAmount }).Where(x => x.Id == headId).ExecuteCommandAsync();
        }
    }
}